const {
  readdirSync,
  copyFileSync
} = require('fs');
const {
  outerPath: {
    jsPath,
    cssPath,
    htmlPath
  },
  innerDirPath: {
    jsDir,
    cssDir,
    htmlDir
  }
} = require('../config');
const {
  createIndexHtml
} = require('../compiler');

function initFiles(options) {
  copyFiles('css');
  copyFiles('js');
  createIndexHtml(options);
  copyWelcomePage();
}

//拷贝文件
function copyFiles(field) {
  //可以直接拷贝的目录文件有 js | css
  //读取目录
  //被拷贝目录
  let _innerFiles = [];
  //目标目录
  let _outterFiles = [];
  //inner
  let _dir = '';
  //outter
  let _path = '';

  //field 用来区别是js目录还是css目录
  switch (field) {
    case 'css':
      _dir = cssDir;
      _path = cssPath;

      //readdirSync返回一个数组['名称1.css','名称2.css']
      //读取源文件css目录 
      _innerFiles = readdirSync(cssDir);
      //读取目标文件css目录
      _outterFiles = readdirSync(cssPath);
      break;
    case 'js':
      _dir = jsDir;
      _path = jsPath;
      //读取源文件css目录 
      _innerFiles = readdirSync(jsDir);
      //读取目标文件css目录
      _outterFiles = readdirSync(jsPath);
      break;
    default:
      break;
  }

  /**
   * console.log(_innerFiles);
   * [
   *   'github-gist.min.css',
   *   'github-markdown.min.css',
   *   'index.css',
   *   'md.css
   * ]
   */

  // console.log(_outterFiles); []

  // console.log(_dir);
  //C:\frontEnd\demo\vite-doc-md-creator-demo\dev\vite-doc-creator\temp_files\css
  //C:\frontEnd\demo\vite-doc-md-creator-demo\dev\vite-doc-creator\temp_files\js

  // console.log(_path);
  //C:\frontEnd\demo\vite-doc-md-creator-demo\src\css
  //C:\frontEnd\demo\vite-doc-md-creator-demo\src\js

  //遍历每一个文件
  _innerFiles.map(function (innerFile) {
    //当目标目录里的文件不存在时
    if (_outterFiles.indexOf(innerFile) === -1) {
      //复制文件
      /**
       * copyFileSync()
       * @params1 源文件路径
       * @params2 需创建的目标文件路径及名称
       * @params3 0
       * @params4 错误信息回调
       */
      copyFileSync(_dir + '/' + innerFile, _path + '/' + innerFile, 0, function (err) {
        if (err) {
          throw new Error('File is failed to copy.', err);
        }
      });

    }
  });

}

//拷贝欢迎页面
function copyWelcomePage() {
  //读取目标目录
  const _htmlFiles = readdirSync(htmlPath);

  //当目标html目录没有welcome.html文件时
  if (_htmlFiles.length === 0) {
    copyFileSync(htmlDir + '/welcome.html', htmlPath + '/welcome.html', 0, function (err) {
      if (err) {
        throw new Error('File is failed to copy.', err);
      }
    });
  }
}

module.exports = initFiles;